package concurrent;

import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * TODO 简单说明
 *
 * @author yangyang
 * @date 2017/8/1 16:11
 * @email kekecany@163.com
 */
// read-only object does not require synchronization
class Customer {
    private final int serviceTime;

    public Customer(int serviceTime) {
        this.serviceTime = serviceTime;
    }

    public int getServiceTime() {
        return serviceTime;
    }

    @Override
    public String toString() {
        return "[" + serviceTime + "]";
    }
}

class CustomerLine extends ArrayBlockingQueue<Customer> {
    public CustomerLine(int maxLineSize) {
        super(maxLineSize);
    }

    @Override
    public String toString() {
        if (size() <= 0) {
            return "[Empty]";
        }
        StringBuilder stringBuilder = new StringBuilder();
        this.forEach(stringBuilder::append);
        return stringBuilder.toString();
    }
}
class CustomerGenerator implements Runnable {
    private CustomerLine customers;
    private Random random = new Random(47);

    public CustomerGenerator(CustomerLine customers) {
        this.customers = customers;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                TimeUnit.MILLISECONDS.sleep(random.nextInt(300));
                customers.put(new Customer(random.nextInt(1000)));
            }
        } catch (InterruptedException e) {
            System.out.println("CustomerGenerator interrupts");
        }
        System.out.println("CustomerGenerator terminating");
    }
}
class Teller implements Runnable, Comparable<Teller> {

    private static int counter = 0;
    private final int id = counter++;
    private int customersServed = 0;
    private boolean servingCustomerLine = true;
    private CustomerLine customers;

    public Teller(CustomerLine customers) {
        this.customers = customers;
    }
    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                Customer customer = customers.take();
                TimeUnit.MILLISECONDS.sleep(customer.getServiceTime());
                synchronized (this) {
                    customersServed++;
                    while (!servingCustomerLine) {
                        wait();
                    }
                }
            }
        } catch (InterruptedException e) {
            System.out.println(this + "interrupted");
        }
        System.out.println(this + "terminating");
    }
    public synchronized void dosomethingElse() {
        customersServed = 0;
        servingCustomerLine = false;
    }
    public synchronized void serveCustomLine() {
        assert !servingCustomerLine : "already serving: " + this;
        servingCustomerLine = true;
        notifyAll();
    }

    @Override
    public String toString() {
        return "Teller " + id + " ";
    }
    public String shortString() {
        return "T" + id + " ";
    }

    @Override
    public synchronized int compareTo(Teller o) {
        return customersServed < o.customersServed ? -1 :
                (customersServed > o.customersServed ? 1 : 0);
    }
}

class TellerManager implements Runnable {

    private ExecutorService executorService;
    private CustomerLine customers;
    private PriorityQueue<Teller> workingTellers = new PriorityQueue<>();
    private Queue<Teller> tellersDoingSomeOtherThings = new LinkedList<>();
    private int adjustmentPeriod;
    private static Random random = new Random(47);

    public TellerManager(ExecutorService executorService, CustomerLine customers, int adjustmentPeriod) {
        this.executorService = executorService;
        this.customers = customers;
        this.adjustmentPeriod = adjustmentPeriod;
        // start with a single teller
        Teller teller = new Teller(customers);
        executorService.execute(teller);
        workingTellers.add(teller);
    }

    public void adjustTellerNumber() {
        // This is actually a control system. By adjusting numbers,
        // you can reveal stability issues in the control mechanism.
        // if line is too long, add another teller
        if (customers.size() / workingTellers.size() > 2) {
            // if tellers are on break or doing another job, bring one back
            if (tellersDoingSomeOtherThings.size() > 0) {
                Teller teller = tellersDoingSomeOtherThings.remove();
                teller.serveCustomLine();
                workingTellers.offer(teller);
                return;
            }
            // else, create(hire) a new teller
            Teller teller = new Teller(customers);
            executorService.execute(teller);
            workingTellers.add(teller);
            return;
        }
        // if line is short enough, remove a teller
        if (workingTellers.size() > 1 && customers.size() / workingTellers.size() < 2) {
            reassignOneTeller();
        }
        if (customers.size() == 0) {
            while (workingTellers.size() > 1) {
                reassignOneTeller();
            }
        }
    }
    // give a teller a different job or a break
    private void reassignOneTeller() {
        Teller teller = workingTellers.poll();
        teller.dosomethingElse();
        tellersDoingSomeOtherThings.add(teller);
    }
    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                TimeUnit.MILLISECONDS.sleep(adjustmentPeriod);
                adjustTellerNumber();
                System.out.println(customers + "{");
                for (Teller teller : workingTellers) {
                    System.out.print(teller.shortString() + " ");
                }
                System.out.println("}");
            }
        } catch (InterruptedException e) {
            System.out.println(this + "interrupted");
        }
        System.out.println(this + "terminating");
    }
    @Override
    public String toString() {
        return "TellerManager";
    }
}

public class BankTellerSimulation {
    private final static int MAX_LINE_SIZE = 50;
    private final static int ADJUSTMENT_PERIOD = 1000;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        CustomerLine customers = new CustomerLine(MAX_LINE_SIZE);
        executorService.execute(new CustomerGenerator(customers));
        executorService.execute(new TellerManager(executorService, customers, ADJUSTMENT_PERIOD));
        TimeUnit.SECONDS.sleep(50);
        executorService.shutdownNow();
    }
}
